import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:hixing_app/utils/permission.dart';
import 'package:hixing_app/views/test_view/ble_machine/scan_ble.dart';
import 'package:permission_handler/permission_handler.dart';

import 'ble_off_page.dart';

class BleChannel extends StatefulWidget {
  @override
  _BleChannelState createState() => _BleChannelState();
}

class _BleChannelState extends State<BleChannel> {
  BluetoothAdapterState _adapterState = BluetoothAdapterState.unknown;
  late StreamSubscription<BluetoothAdapterState> _adapterStateStateSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 打开蓝牙
    _adapterStateStateSubscription =
        FlutterBluePlus.adapterState.listen((state) {
      _adapterState = state;
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _adapterStateStateSubscription.cancel();
  }

  void scanBle() {
    // listen to scan results
// Note: `onScanResults` only returns live scan results, i.e. during scanning
// Use: `scanResults` if you want live scan results *or* the results from a previous scan
    var subscription = FlutterBluePlus.onScanResults.listen(
      (results) {
        if (results.isNotEmpty) {
          ScanResult r = results.last; // the most recently found device
          print(
              '${r.device.remoteId}: "${r.advertisementData.advName}" found!');
          print("当前蓝牙列表");
        }
      },
      onError: (e) => print(e),
    );
// cleanup: cancel subscription when scanning stops
    FlutterBluePlus.cancelWhenScanComplete(subscription);
  }

  @override
  Widget build(BuildContext context) {
    Widget child =
        _adapterState == BluetoothAdapterState.on ? ScanBle() : BleOffPage();
    return child;
  }
}
